<template>
    <ul class="nav nav-list cascader-dropdown-item">
        <ul-menu-item v-for="item in data" :key="item.id" :data="item" :setVal="setVal"
                      @click.native.stop="clickItem(item)" :select="selectVal"/>
        <li v-if="(data && data.length) === false"><p class="text-center text-muted">没有任何可以选择</p></li>
    </ul>
</template>

<script>
    /* eslint-disable no-undef */

    import UlMenuItem from './MenuItem.vue';

    export default {
        name: 'ul-menu',
        components: {UlMenuItem},
        data () {
            return {
                setVal: {},
                selectVal: {}
            };
        },
        methods: {
            clickItem (item) {
                this.setVal = item;
            }
        },
        props: {
            data: {type: Array},
            index: {type: Number, default: -1},
            selectValue: {
                type: Object,
                default: () => {
                    return {};
                }
            }
        },
        watch: {
            setVal (newVal) {
                this.$emit('input', newVal);
            },
            index (newVal) {
                if (this.data && this.data.length && this.index >= 0 && this.index < this.data.length) {
                    this.selectVal = this.data[newVal];
                    this.$nextTick(() => {
                        let ul = $(this.$el);
                        let li = $('li > a[class*="selected"]', ul).parent();
                        let height = ul.height();
                        let scrollTop = ul.scrollTop();
                        let positionTop = li.position().top;
                        let fixed = 0;
                        if (height < positionTop) {
                            fixed = positionTop - height + 33 + scrollTop;
                            if (fixed <= scrollTop) {
                                return;
                            }
                        } else if (positionTop < 0) {
                            fixed = scrollTop + positionTop;
                        } else {
                            return;
                        }
                        ul.animate({scrollTop: fixed}, 200);
                    });
                } else {
                    this.selectVal = {};
                }
            },
            selectValue (newVal) {
                this.setVal = newVal;
            }
        },
        mounted () {
            if (this.data && this.data.length && this.index > -1) {
                this.selectVal = this.data[this.index];
            }
            this.setVal = this.selectValue;
        }
    };
</script>
